import axios from 'axios';
import qs from 'qs';
import { _localUserInfo } from '../util/authUserInfo/userInfo';

const instance = axios.create({
    // localUrl, //baseURL会在发起请求的时候自动拼接在url前面
    timeout: 30000,
});

instance.interceptors.request.use(
    //请求拦截 统一加密
    (config) => {
        // console.log(config)
        return config;
    },
    (err) => {
        return Promise.reject(err);
    }
);

instance.interceptors.response.use(
    //响应拦截
    function (res) {
        // console.log(res);
        return Promise.resolve(res);
    },

    function (err) {
        // console.log('ss')
        let { response } = err;
        if (response) {
            // 服务器返回结果
            switch (response.status) {
                //判断错误编码
                case 401:
                    break;
                case 403:
                    break;
                case 404: //
                    break;
            }
        } else {
            // console.log('ss')
            // 服务器崩溃或者断网
            if (!window.navigator.onLine) {
                // 断网处理  可以跳转到断网页面
                return;
            }
        }
        return Promise.reject(err);
    }
);

class oldHTTP {
    static post(url: string, data: string, type?: string, is?: boolean): Promise<object> {
        // let userKey: any;
        // if (is) {
        //   userKey = '';
        // } else {
        //   let userInfo = _localUserInfo();
        //   userKey = userInfo.zwdtsw_user_id;
        // }
        // console.log(url);
        if (!(type && type === 'uploadFile')) {
            data = qs.stringify(data);
        }
        return new Promise((resolve, reject) => {
            instance
                .post(url, data, {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8;',
                        // userKey,
                    },
                })
                .then((res) => {
                    resolve(res.data);
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }

    static get(url: string, data: object, type?: string, is?: boolean): Promise<any> {
        // let userKey: any;
        // if (is) {
        //   userKey = '';
        // } else {
        //   let userInfo = _localUserInfo();
        //   userKey = userInfo.zwdtsw_user_id;
        // }
        return new Promise((resolve, reject) => {
            instance
                .get(url, {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8;',
                        // userKey,
                    },
                    params: data,
                })
                .then((res) => {
                    resolve(res.data);
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }
}

export { oldHTTP };
